package com.edfu.core.commons.persistence.impl;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;

import com.edfu.core.commons.persistence.api.ICategoryMgtPersistence;
import com.edfu.core.commons.persistence.entity.CategoryEntity;

@Repository
public class CategoryMgtPersistenceImpl implements ICategoryMgtPersistence {
	
	private static Logger logger = LoggerFactory.getLogger(CategoryMgtPersistenceImpl.class);
	
	private EntityManager entityManager;
	
//	@Autowired
//	private MongoTemplate mongoTemplate;
	
	@PersistenceContext
	public void setEntityManager(EntityManager entityManager) {
		this.entityManager = entityManager;
	}
	
	@Override
	public CategoryEntity createCategory(CategoryEntity ce) {
		logger.debug("Creating Category " + ce.getName());
		return entityManager.merge(ce);
	}

	@Override
	public CategoryEntity updateCategory(CategoryEntity ce) {
		return entityManager.merge(ce);
	}

	@Override
	public void removeCategory(CategoryEntity ce) {
		entityManager.remove(ce);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<CategoryEntity> getCategories() {
		Query query = entityManager.createQuery("select t from CategoryEntity t");		
		
		return query.getResultList();
	}

	@Override
	public CategoryEntity getCategory(long categoryId) {
		return entityManager.find(CategoryEntity.class, categoryId);
	}

	@SuppressWarnings("unchecked")
	@Override
	public CategoryEntity getCategory(String categoryName) {
		Query query = entityManager.createQuery("select t from CategoryEntity t where t.name = :categoryName");
		query.setParameter("categoryName", categoryName);
		List<CategoryEntity> entityList = query.getResultList();
		CategoryEntity ce = null;
		
		if (entityList != null && entityList.size() > 0) {
			ce = entityList.get(0);
		}
		
		return ce;
	}

	@Override
	public List<CategoryEntity> addCategories(CategoryEntity parentCategory, List<CategoryEntity> categories) {
		List<CategoryEntity> tcList = new ArrayList<CategoryEntity>();
		CategoryEntity tc = null;
		for (CategoryEntity ce : categories) {
			ce.setParentCategory(parentCategory);
			tc = entityManager.merge(ce);
			tcList.add(tc);
		}
		
		return tcList;
	}

	@Override
	public boolean isCategoryUnique(String categoryName) {
		return getCategory(categoryName) != null ? false : true;
	}

}
